package com.shujia.MapReduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.ArrayList;

public class Demo03Join {
    // Map端
    public static class MyMapper extends Mapper<LongWritable, Text, Text, Text> {
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context) throws IOException, InterruptedException {
            String[] splits = value.toString().split(",");
            // 学生的id作为Map输出的key
            String id = splits[0];
            String outputValue = "";
            // 通过splits.length 判断当前处理的这条数据到底是属于students还是score的数据
            if (splits.length == 5) {
                // students学生信息数据
                outputValue = "#" + value;
            } else if (splits.length == 3) {
                // score学生分数数据
                outputValue = "$" + value;
            }
            context.write(new Text(id), new Text(outputValue));
        }
    }

    // Reduce端
    public static class MyReducer extends Reducer<Text, Text, Text, Text> {
        @Override
        protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws IOException, InterruptedException {
            // 从values中区分出学生信息数据及学生分数数据
            /*
             * key : 1500100001
             * values : #1500100001,施笑槐,22,女,文科六班
             *          $1500100001,1000001,98
             *          $1500100001,1000002,5
             *          $1500100001,1000003,137
             *          $1500100001,1000004,29
             *          $1500100001,1000005,85
             *          $1500100001,1000006,52
             */
            // 因为Iterable<Text> values只能被遍历一次，但需要使用两次
            // 已知values的数据量不是很大，所以直接将values的数据放入List
            ArrayList<String> valueList = new ArrayList<>();
            for (Text value : values) {
                valueList.add(value.toString());
            }

            // 提取学生信息：姓名、班级
            String name = "";
            String clazz = "";
            for (String valueStr : valueList) {
                if (valueStr.contains("#")) {
                    name = valueStr.split(",")[1];
                    clazz = valueStr.split(",")[4];
                }
            }

            for (String valueStr : valueList) {
                if (valueStr.contains("$")) {
                    String subjectId = valueStr.split(",")[1];
                    String subjectScore = valueStr.split(",")[2];
                    // Reduce Join
                    context.write(key, new Text(name + "," + clazz + "," + subjectId + "," + subjectScore));
                }
            }

        }
    }

    // Driver程序，主要负责配置及提交任务
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://master:9000");
        // 指定分隔符为 逗号
        conf.set("mapred.textoutputformat.separator", ",");
        // 创建一个MapReduce的Job
        Job job = Job.getInstance(conf);
        // 配置任务
        // 设置任务运行的名字
        job.setJobName("Demo03Join");
        // 设置任务运行哪一个类
        job.setJarByClass(Demo03Join.class);

        // 配置Map端
        // 指定Map任务运行哪一个类
        job.setMapperClass(MyMapper.class);
        // 配置Map端输出的Key的类型
        job.setMapOutputKeyClass(Text.class);
        // 配置Map端输出的Value的类型
        job.setMapOutputValueClass(Text.class);

        // 配置Reduce端
        // 指定Reduce任务运行哪一个类
        job.setReducerClass(MyReducer.class);
        // 配置Reduce端输出的Key的类型
        job.setOutputKeyClass(Text.class);
        // 配置Reduce端输出的Value的类型
        job.setOutputValueClass(Text.class);

        // 配置输入输出路径
        FileInputFormat.addInputPath(job, new Path("/data/stu/input"));
        FileInputFormat.addInputPath(job, new Path("/data/score/input"));

        Path path = new Path("/data/join/output");
        FileSystem fs = FileSystem.get(conf);
        // 判断输出路径是否存在，存在即删除
        if (fs.exists(path)) {
            fs.delete(path, true);
        }
        // 输出路径已存在会报错
        FileOutputFormat.setOutputPath(job, path);


        // 等待任务运行完成
        job.waitForCompletion(true);

    }
    /*
     * hdfs dfs -mkdir -p /data/score/input
     * hdfs dfs -mkdir -p /data/join/output
     * hdfs dfs -put score.txt /data/score/input/
     * hadoop jar Hadoop-1.0.jar com.shujia.MapReduce.Demo03Join
     */

}
